package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.constants.MQConstants;
import com.heima.common.constants.RedisConstants;
import com.heima.common.dtos.AppHttpCodeEnum;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.search.dtos.UpdateArticleMsg;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.JsonUtils;
import com.heima.utils.common.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

@Service
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Override
    public ResponseResult likesBehavior(LikesBehaviorDto dto) {
        //判断是否登录
        ApUser user = (ApUser) ThreadLocalUtils.get();
        if(user==null){
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }

        String key= RedisConstants.LIKE_BEHAVIOR+dto.getArticleId();

        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(key);

        //判断操作类型
        if (dto.getOperation().equals((short) 0)) {
            boundHashOps.put(user.getId(), JsonUtils.toString(dto));

            //行为触发后发送消息给KafkaStream统计
            UpdateArticleMsg msg = new UpdateArticleMsg();
            msg.setArticleId(dto.getArticleId());
            msg.setType(UpdateArticleMsg.UpdateArticleType.LIKES);

            kafkaTemplate.send(MQConstants.HOT_ARTICLE_INPUT_TOPIC,JsonUtils.toString(msg));

        }else{
            //取消点赞
            boundHashOps.delete(user.getId().toString());
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
